// 树和数组 相关 通用方法

export type TreeNode = {
  id: number;
  parentId: number;
  children: TreeNode[] | undefined;
};

// 数组转树
export const arr2Tree = (flattenArr: TreeNode[]) => {
  const hashTable = new Map<number, TreeNode>();
  flattenArr.forEach((item) => hashTable.set(item.id, { ...item, children: [] }));
  const dataTree: TreeNode[] = [];
  flattenArr.forEach((item) => {
    // 如果 parentId 不是0 (说明是儿子)
    if (item.parentId !== 0) hashTable.get(item.parentId)?.children?.push(hashTable.get(item.id)!);
    // 如果 parentId 是0 (说明有儿子)
    else dataTree.push(hashTable.get(item.id)!);
  });
  // 遍历一遍 hashTable ,把 children 为空数组的 弄成undefined ,避免 ant design pro table 出现展开按钮
  // if (hashTable[item.id].children.length === 0) hashTable[item.id].children = undefined;
  hashTable.forEach((item, key) => {
    if (item.children?.length === 0) {
      hashTable.get(key)!.children = undefined;
    }
  });
  return dataTree;
};
